package com.accessibleworlds.gateway;

import com.accessibleworlds.blind.BlindUserMainPage;
import com.accessibleworlds.user.Options;
import com.accessibleworlds.user.StartPage;
import com.accessibleworlds.user.UserPage;
import com.accessibleworlds.util.Connections;
import com.accessibleworlds.util.SharedVariables;
import com.accessibleworlds.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Login extends Activity implements OnClickListener{
	/**
	 * View elements
	 */
	private TextView title, emailTitle, passwordTitle, forgottenPass;
	private EditText emailEdit, passwordEdit, emailEditForgotten, emailEditActivation;
	private CheckBox blindUserModeCheck;
	private Button submit, cancel;
	
	private boolean blindUserModeBoolean; 
	private boolean isInvisible;

	private ProgressDialog progressDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if(getWindow().getAttributes().softInputMode==WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED)	{
		    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		}
		
		setContentView(R.layout.login);
		
		isInvisible = getIntent().getExtras().getBoolean("isInvisible");
		
		initializeVariables();
        changeLanguage();
        
        if(isInvisible) {
        	moveTaskToBack(true);
        }
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		isInvisible=false;
        changeLanguage();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		isInvisible = true;
	}
	
	@Override
	public void onBackPressed() {
		Intent intent = new Intent(this,StartPage.class);
		Bundle bundle = new Bundle();
		bundle.putString("previousID", SharedVariables.loginID);
		intent.putExtras(bundle);
		startActivity(intent);
		overridePendingTransition(R.anim.fade, R.anim.hold);
		finish();
	}
	
	/**
	 * This is for initializing views.
	 */
	private void initializeVariables() {
		title = (TextView)findViewById(R.id.login);
		emailTitle = (TextView)findViewById(R.id.loginEmailTitle);
		passwordTitle = (TextView)findViewById(R.id.loginPasswordTitle);
		forgottenPass = (TextView)findViewById(R.id.ForgottenPass);
		
		emailEdit = (EditText)findViewById(R.id.loginEmailEdit);
		passwordEdit = (EditText)findViewById(R.id.loginPasswordEdit);
		
		blindUserModeCheck = (CheckBox)findViewById(R.id.loginBlindUserModeCheck);
		
		submit = (Button)findViewById(R.id.loginSubmit);
		cancel = (Button)findViewById(R.id.loginCancel);
		
		forgottenPass.setOnClickListener(this);
        submit.setOnClickListener(this);
		cancel.setOnClickListener(this);
		
		progressDialog = new ProgressDialog(Login.this);
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(false);
	}
	
	/**
	 * This is for changing text of the views.
	 */
	private void changeLanguage() {
		title.setText(getResources().getStringArray(R.array.loginUpper)[SharedVariables.currentLanguage]);
		emailTitle.setText(getResources().getStringArray(R.array.email)[SharedVariables.currentLanguage]);
		passwordTitle.setText(getResources().getStringArray(R.array.password)[SharedVariables.currentLanguage]);
		blindUserModeCheck.setText(getResources().getStringArray(R.array.loginAsBlindUserMode)[SharedVariables.currentLanguage]);
		
		submit.setText(getResources().getStringArray(R.array.submit)[SharedVariables.currentLanguage]);
		cancel.setText(getResources().getStringArray(R.array.cancel)[SharedVariables.currentLanguage]);
		
		progressDialog.setMessage(getResources().getStringArray(R.array.loadingMessage)[SharedVariables.currentLanguage]);
	}
	
	public void onClick(View v) {
		if(v.getId() == submit.getId()) {
			InputMethodManager imm =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(emailEdit.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(passwordEdit.getWindowToken(), 0);

			blindUserModeBoolean = blindUserModeCheck.isChecked(); 
			
			new LoginTask().execute(new String []{emailEdit.getText().toString(), passwordEdit.getText().toString()});
		}
		else if(v.getId()==cancel.getId()){
			Intent intent = new Intent(this,StartPage.class);
			Bundle bundle = new Bundle();
			bundle.putString("previousID", SharedVariables.loginID);
			intent.putExtras(bundle);
			startActivity(intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
			finish();
		}
		else if(v.getId() == forgottenPass.getId()) {
			AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
			alertDialog.setTitle(getResources().getStringArray(R.array.forgottenPasswordTitle)[SharedVariables.currentLanguage]);
			alertDialog.setMessage(getResources().getStringArray(R.array.forgottenPasswordMessage)[SharedVariables.currentLanguage]);
			emailEditForgotten = new EditText(Login.this);
			emailEditForgotten.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
			emailEditForgotten.setText(emailEdit.getText().toString());
			alertDialog.setView(emailEditForgotten);
			alertDialog.setButton(getResources().getStringArray(R.array.submit)[SharedVariables.currentLanguage], new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					String emailStringForgotten = emailEditForgotten.getText().toString();
					if(emailStringForgotten.length()>0 && emailStringForgotten.length()<=100) {
						new ForgottenTask().execute(emailStringForgotten);
					}
					else {
						Toast.makeText(Login.this, getResources().getStringArray(R.array.emailProblem)[SharedVariables.currentLanguage], Toast.LENGTH_LONG).show();
					}
				}
			});
			alertDialog.show();
		}
	}

	/**
	 * This is for checking variables without using views.
	 * 
	 * @param emailString : This is email of the user.
	 * @param passwordString : This is password of the user.
	 * @return true or false
	 */
	private boolean checkVariablesBackground(String emailString, String passwordString) {
		boolean check = true;
		
		if(!(emailString.length()>0 && emailString.length()<=100)) {
			check = false;
		}
		
		if(!(passwordString.length()>0 && passwordString.length()<=255)) {
			check = false;
		}

		return check;
	}
	
	public class LoginTask extends AsyncTask<String, Integer, String>{
		private String [] takenData = null;
		private String emailString = "";
		private String passwordString = "";
		
		protected void onPreExecute() {
			progressDialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			emailString = params[0];
			passwordString = params[1];
			
			if(Connections.serviceStatus()) {
				if(checkVariablesBackground(emailString,passwordString)) {
					try {
						String url = Connections.URI+Connections.login;
						String [] parameters = {"accessCode","email","password"};
						String [] paramaterValues = {SharedVariables.accessCode,emailString,passwordString};
						
						takenData = Connections.connection(url,parameters,paramaterValues);
						
						if(takenData.length==0) {
							publishProgress(1);
						}
						else if("Not Exist!!!".equalsIgnoreCase(takenData[1])) {
							publishProgress(1);
							return "Not Exist!!!";
						}
						else if("Not Activated!!!".equalsIgnoreCase(takenData[1])) {
							publishProgress(2);
							return "Not Activated!!!";
						}
						else if("OK".equalsIgnoreCase(takenData[0])) {
							publishProgress(3);
							return "OK";
						}
						else {
							publishProgress(4);
						}
					} catch (Exception e) {
						publishProgress(1);
					}
				}
				else {
					publishProgress(1);
				}
			}
			else {
				publishProgress(0);
			}
			return "Fail";
		}

		protected void onProgressUpdate(Integer... progress) {
			if(progress[0] == 0) {
				progressDialog.dismiss();
				
			}
			else if(progress[0] == 1) {
				progressDialog.dismiss();
				AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
				alertDialog.setTitle(getResources().getStringArray(R.array.forgottenPasswordTitle)[SharedVariables.currentLanguage]);
				alertDialog.setMessage(getResources().getStringArray(R.array.forgottenPasswordMessage)[SharedVariables.currentLanguage]);
				emailEditForgotten = new EditText(Login.this);
				emailEditForgotten.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
				emailEditForgotten.setText(emailString);
				alertDialog.setView(emailEditForgotten);
				alertDialog.setButton(getResources().getStringArray(R.array.submit)[SharedVariables.currentLanguage], new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String emailStringForgotten = emailEditForgotten.getText().toString();
						if(emailStringForgotten.length()>0 && emailStringForgotten.length()<=100) {
							new ForgottenTask().execute(emailStringForgotten);
						}
						else {
							Toast.makeText(Login.this, getResources().getStringArray(R.array.emailProblem)[SharedVariables.currentLanguage], Toast.LENGTH_LONG).show();
						}
					}
				});
				alertDialog.show();
			}
			else if(progress[0]==2) {
				progressDialog.dismiss();
				AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
				alertDialog.setTitle(getResources().getStringArray(R.array.validationTitle)[SharedVariables.currentLanguage]);
				alertDialog.setMessage(getResources().getStringArray(R.array.validationMessage)[SharedVariables.currentLanguage]);
				emailEditActivation = new EditText(Login.this);
				emailEditActivation.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
				emailEditActivation.setText(emailString);
				alertDialog.setView(emailEditActivation);
				alertDialog.setButton(getResources().getStringArray(R.array.submit)[SharedVariables.currentLanguage], new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String emailStringActivation = emailEditActivation.getText().toString();
						if(emailStringActivation.length()>0 && emailStringActivation.length()<=100) {
							new ActivationTask().execute(emailStringActivation);
						}
						else {
							Toast.makeText(Login.this, getResources().getStringArray(R.array.emailProblem)[SharedVariables.currentLanguage], Toast.LENGTH_LONG).show();
						}
					}
				});
				alertDialog.show();
			}
			else if(progress[0]==3) {
				progressDialog.dismiss();
				Intent intent = null;
				if(blindUserModeBoolean) {
					intent = new Intent(Login.this,BlindUserMainPage.class);
				}
				else {
					intent = new Intent(Login.this,UserPage.class);
				}
				Bundle bundle = new Bundle();
				bundle.putString("previousID", SharedVariables.loginID);
				bundle.putBoolean("isInvisible", isInvisible);
				intent.putExtras(bundle);
				
				SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
				SharedPreferences.Editor editor = preferences.edit();
				editor.putBoolean("autoLogin", true);
				editor.putString("email", emailString);
				editor.putString("password", passwordString);
				editor.putBoolean("blindUserMode", blindUserModeBoolean);
				editor.commit();
				
				SharedPreferences savePreferences = getSharedPreferences(SharedVariables.fileName, MODE_PRIVATE);
				SharedPreferences.Editor saveEditor = savePreferences.edit();
				saveEditor.putString("userID", takenData[1]);
				saveEditor.putString("email", takenData[2]);
				saveEditor.putString("password", takenData[3]);
				saveEditor.putString("lastName", takenData[4]);
				saveEditor.putString("firstName", takenData[5]);
				saveEditor.putString("birthday", takenData[6]);
				saveEditor.commit();
				
				startActivity(intent);
				overridePendingTransition(R.anim.fade, R.anim.hold);
				finish();
				
			}
			else if(progress[0]==4) {
				progressDialog.dismiss();
				Toast.makeText(Login.this, getResources().getStringArray(R.array.connectionProblem)[SharedVariables.currentLanguage], Toast.LENGTH_LONG).show();
			}
		}
		
		protected void onPostExecute(String result) {}
	}
	
	public class ForgottenTask extends AsyncTask<String, Integer, String>{
		private String [] takenData = null;
		private String emailStringForgotten = "";
		
		protected void onPreExecute() {
			progressDialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			emailStringForgotten = params[0];
			
			if(Connections.serviceStatus()) {
				try {
					String url = Connections.URI+Connections.forgottenPassword;
					String [] parameters = {"accessCode","email"};
					String [] paramaterValues = {SharedVariables.accessCode,emailStringForgotten};
					
					takenData = Connections.connection(url,parameters,paramaterValues);
					
					if("OK".equalsIgnoreCase(takenData[0])) {
						publishProgress(2);
						return "OK";
					}
					else {
						publishProgress(1);
					}
					
				} catch (Exception e) {
					publishProgress(1);
				}
			}
			else {
				publishProgress(0);
			}
			return "Fail";
		}
		
		protected void onProgressUpdate(Integer... progress) {
			if(progress[0] == 0) {
				progressDialog.dismiss();
				AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
				alertDialog.setTitle(getResources().getStringArray(R.array.connectionProblem)[SharedVariables.currentLanguage]);
				alertDialog.setMessage(getResources().getStringArray(R.array.connectionProblemException)[SharedVariables.currentLanguage]);
				alertDialog.setButton(getResources().getStringArray(R.array.tryAgain)[SharedVariables.currentLanguage], new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						new ForgottenTask().execute(emailStringForgotten);
					}
				});
				alertDialog.setButton2(getResources().getStringArray(R.array.exit)[SharedVariables.currentLanguage], new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						finish();
					}
				});
				alertDialog.show();
			}
			else if(progress[0] == 1) {
				progressDialog.dismiss();
				Toast.makeText(Login.this, getResources().getStringArray(R.array.connectionProblem)[SharedVariables.currentLanguage], Toast.LENGTH_LONG).show();
			}
			else if(progress[0]==2) {
				progressDialog.dismiss();
				Toast.makeText(Login.this, getResources().getStringArray(R.array.forgottenPasswordToast)[SharedVariables.currentLanguage], Toast.LENGTH_LONG).show();
			}
		}
		
		protected void onPostExecute(String result) {}
	}
	
	public class ActivationTask extends AsyncTask<String, Integer, String>{
		private String [] takenData = null;
		private String emailStringActivation = "";
		
		protected void onPreExecute() {
			progressDialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			emailStringActivation = params[0];
			
			if(Connections.serviceStatus()) {
				try {
					String url = Connections.URI+Connections.addressValidation;
					String [] parameters = {"accessCode","email"};
					String [] paramaterValues = {SharedVariables.accessCode,emailStringActivation};
					
					takenData = Connections.connection(url,parameters,paramaterValues);
					
					if("OK".equalsIgnoreCase(takenData[0])) {
						publishProgress(2);
						return "OK";
					}
					else {
						publishProgress(1);
					}
					
				} catch (Exception e) {
					publishProgress(1);
				}
			}
			else {
				publishProgress(0);
			}
			return "Fail";
		}
		
		protected void onProgressUpdate(Integer... progress) {
			if(progress[0] == 0) {
				progressDialog.dismiss();
				AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
				alertDialog.setTitle(getResources().getStringArray(R.array.connectionProblem)[SharedVariables.currentLanguage]);
				alertDialog.setMessage(getResources().getStringArray(R.array.connectionProblemException)[SharedVariables.currentLanguage]);
				alertDialog.setButton(getResources().getStringArray(R.array.tryAgain)[SharedVariables.currentLanguage], new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						new ActivationTask().execute(emailStringActivation);
					}
				});
				alertDialog.setButton2(getResources().getStringArray(R.array.exit)[SharedVariables.currentLanguage], new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						finish();
					}
				});
				alertDialog.show();
			}
			else if(progress[0] == 1) {
				progressDialog.dismiss();
				Toast.makeText(Login.this, getResources().getStringArray(R.array.connectionProblem)[SharedVariables.currentLanguage], Toast.LENGTH_LONG).show();
			}
			else if(progress[0]==2) {
				progressDialog.dismiss();
				Toast.makeText(Login.this, getResources().getStringArray(R.array.activationToast)[SharedVariables.currentLanguage], Toast.LENGTH_LONG).show();
			}
		}
		
		protected void onPostExecute(String result) {}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater mainMenu = getMenuInflater();
		mainMenu.inflate(R.menu.mainmenu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.findItem((R.id.menuOptions)).setTitle(getResources().getStringArray(R.array.options)[SharedVariables.currentLanguage]);
		menu.findItem(R.id.menuOptions).setIcon(R.drawable.optionsicon);
		menu.findItem((R.id.menuExit)).setTitle(getResources().getStringArray(R.array.exit)[SharedVariables.currentLanguage]);
		menu.findItem((R.id.menuExit)).setIcon(R.drawable.exiticon);
		return super.onPrepareOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId()==R.id.menuOptions) {
			Intent intent = new Intent(this,Options.class);
			Bundle bundle = new Bundle();
			bundle.putString("previousID", SharedVariables.loginID);
			intent.putExtras(bundle);
			startActivity(intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
		}
		else if (item.getItemId()==R.id.menuExit) {
			finish();
		}
		return super.onOptionsItemSelected(item);
	}
}
